package com.tbsoft.trail.util;

import static org.apache.commons.digester3.binder.DigesterLoader.newLoader;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.digester3.Digester;
import org.apache.commons.digester3.annotations.FromAnnotationsRuleModule;
import org.apache.commons.digester3.annotations.rules.ObjectCreate;
import org.apache.commons.digester3.binder.DigesterLoader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
 * @desc 根据xml转换成bean的工具类
 * @author lizhenhua
 *
 */
public class XmlParse {
	@SuppressWarnings("unchecked")
	private List returnList = new ArrayList();
	private static final Log log = LogFactory.getLog(XmlParse.class);

	public static XmlParse getInstance() {
		return new XmlParse();
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> xmlToBean(final Class<T> beanClass, final String xml,
			final String encode) throws Exception {
		DigesterLoader loader = newLoader(new FromAnnotationsRuleModule() {
			@Override
			protected void configureRules() {
				bindRulesFrom(beanClass);
			}
		});
		Digester digester = loader.newDigester();

		ObjectCreate objectCreate = (ObjectCreate) beanClass
				.getAnnotation(ObjectCreate.class);
		digester.addSetNext(objectCreate.pattern(), "addToList");

		digester.push(this);
		try {
			InputStream in = new ByteArrayInputStream(xml.getBytes(encode));
			log.debug(xml);
			digester.parse(in);
		} catch (Exception ex) {
			log.error("从XML转换成Bean发生错误, XML报文：" + xml + ex.getMessage());
			throw new Exception("从XML转换成Bean发生错误" + ex.getMessage(), ex
					.getCause());

		}

		return this.returnList;
	}
	
	@SuppressWarnings("unchecked")
	public void addToList(Object o) {
        returnList.add(o);
    }
}
